<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="1300px"
      append-to-body
      :before-close="close"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="isDetail">
        <el-descriptions title="房源信息"></el-descriptions>
        <div class="form">
          <el-form-item label="楼盘" prop="estateId">
            <el-input
              style="width: 160px; margin-right: 10px"
              v-model="form.estateName"
              placeholder="请选择楼盘"
              readonly
            ></el-input>
            <el-button
              type="primary"
              icon="el-icon-office-building"
              @click="dialogEstate = true"
              size="small"
            >选择楼盘
            </el-button
            >
          </el-form-item>
          <el-form-item label="楼栋、单元" label-width="130" prop="houseInfo">
            <el-cascader
              v-model="form.houseInfo"
              ref="houseInfo"
              :props="{
                value: 'id',
                label: 'name',
              }"
              :options="estateList"
              @change="handleChange"
              @visible-change="checkedRegion"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="所在楼层" prop="floors">
            <el-select
              v-model="form.floors"
              placeholder="请选择"
              @visible-change="checkedHouseInfo"
            >
              <el-option
                v-for="dict in floorList"
                :key="dict.value"
                :label="dict"
                :value="dict"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="房间号" prop="roomNumber">
            <el-input v-model="form.roomNumber" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="面积" prop="houseArea">
            <el-input
              v-model="form.houseArea"
              placeholder="请输入"
              v-input.float="2"
              @change="(e)=>form.houseArea = Number(e)"
            />
          </el-form-item>
          <el-form-item label="朝向" prop="houseOrientation">
            <el-select v-model="form.houseOrientation" placeholder="请选择" clearable>
              <el-option
                v-for="dict in dict.type.house_orientation"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <!-- <el-input v-model="form.houseOrientation" placeholder="请输入" /> -->
          </el-form-item>
          <el-form-item label="户型" prop="roomType">
            <el-input
              v-model="form.roomType"
              style="width: 110px"
              placeholder=""
              v-input.int
            >
              <span slot="append">室</span>
            </el-input>
            <el-input
              v-model="form.hall"
              style="width: 110px"
              placeholder=""
              v-input.int
            >
              <span slot="append">厅</span>
            </el-input>
            <el-input
              v-model="form.toilet"
              style="width: 110px"
              placeholder=""
              v-input.int
            >
              <span slot="append">卫</span>
            </el-input>
          </el-form-item>
          <el-form-item label="可住人数" prop="checkInNumber">
            <el-input
              type="number"
              v-model.number="form.checkInNumber"
              placeholder=""
            >
              <span slot="append">人</span>
            </el-input>
          </el-form-item>
        </div>
        <el-descriptions title="附加信息"></el-descriptions>
        <div class="form">
          <el-form-item label="水表号" prop="waterMeterNumber">
            <el-input
              v-model="form.waterMeterNumber"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="电表号" prop="electricMeterNumber">
            <el-input
              v-model="form.electricMeterNumber"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="燃气表号" prop="gasMeterNumber">
            <el-input
              v-model="form.gasMeterNumber"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="房屋租赁许可证号" prop="rentalLicenseNumber" label-width="130">
            <el-input
              v-model="form.rentalLicenseNumber"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="房源核验码" prop="houseCheckCode" label-width="130">
            <el-input
              v-model="form.houseCheckCode"
              placeholder="请输入"
            />
          </el-form-item>
        </div>
        <el-descriptions title="合作信息"></el-descriptions>
        <div class="form">
          <el-form-item label="合作方式" prop="cooperationType">
            <el-select
              v-model="form.cooperationType"
              placeholder="请选择"
              @change="checkedCooperationType"
              :disabled="!!roomId"
            >
              <el-option
                v-for="dict in dict.type.cooperation_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="收费方式" prop="chargeType" v-if="form.cooperationType == '2'">
            <el-select
              v-model="form.chargeType"
              placeholder="请选择"
            >
              <el-option
                v-for="dict in dict.type.charge_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <div v-if="form.cooperationType == '2'">
            <el-form-item label="账单服务费" prop="serviceCharge" v-if="form.chargeType == '1'" label-width="130">
              <el-input
                v-model="form.serviceCharge"
                placeholder=""
                v-input.float="1"
                @change="(e)=>form.serviceCharge = Number(e)"
              >
                <span slot="append">%</span>
              </el-input>
            </el-form-item>
            <el-form-item label="费用金额" prop="feeAmount" v-if="form.chargeType == '2'">
              <el-input
                v-model="form.feeAmount"
                placeholder=""
                v-input.float="2"
                @change="(e)=>form.feeAmount = Number(e)"
              >
                <span slot="append">元</span>
              </el-input>
            </el-form-item>
          </div>
          <div v-if="form.cooperationType == '2'">
            <el-form-item label="最晚付款日期" prop="latestPaymentDate" v-if="form.chargeType == '2'">
              <el-date-picker
                v-model="form.latestPaymentDate"
                type="date"
                placeholder="请选择"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :picker-options="lastPaymentDateOptions"
              ></el-date-picker>
            </el-form-item>
          </div>
        </div>
        <el-descriptions title="房源归属"></el-descriptions>
        <div class="form">
          <el-form-item label="房管家" prop="houseManagerId">
            <el-select
              v-model="form.houseManagerId"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="dict in houseManagerList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="业主" prop="proprietorUserId">
            <el-select
              v-model="form.proprietorUserId"
              placeholder="请选择"
              clearable
              :disabled="!!roomId"
            >
              <el-option
                v-for="dict in proprietorList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-descriptions title="房屋设施"></el-descriptions>
        <el-button
          style="margin-bottom: 10px"
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="addfacilities"
        >新增
        </el-button
        >

        <el-table :data="form.facilitiesItemList" style="width: 100%">
          <el-table-column prop="name" label="设施名称">
            <template slot-scope="scope">
              <el-form-item
                label=""
                label-width="0"
                :prop="'facilitiesItemList.' + scope.$index + '.facilitiesId'"
                :rules="[
                  {
                    required: true,
                    message: '请选择房屋设施',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  v-model="form.facilitiesItemList[scope.$index].facilitiesId"
                  placeholder="请选择房屋设施"
                >
                  <el-option
                    v-for="(facility, index) in facilitiesMap"
                    :key="index"
                    :label="facility.facilitiesName"
                    :value="facility.facilitiesId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="amount1" label="数量">
            <template slot-scope="scope">
              <el-form-item
                label-width="0"
                label=""
                :prop="
                  'facilitiesItemList.' + scope.$index + '.facilitiesNumber'
                "
                :rules="[
                  {
                    required: true,
                    message: '请输入数量',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model.number="
                    form.facilitiesItemList[scope.$index].facilitiesNumber
                  "
                  placeholder="请输入"
                  type="number"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="amount2" label="单价">
            <template slot-scope="scope">
              <el-form-item
                label=""
                label-width="0"
                :prop="
                  'facilitiesItemList.' + scope.$index + '.facilitiesPrice'
                "
                :rules="[
                  {
                    required: true,
                    message: '请输入单价',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model.number="
                    form.facilitiesItemList[scope.$index].facilitiesPrice
                  "
                  placeholder="请输入"
                  type="number"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="danger"
                size="mini"
                style="margin-bottom: 22px"
                @click="delfacilities(scope.$index)"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!isDetail">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <selectEstate v-model="dialogEstate" @success="successHandel"/>
  </div>
</template>
<script>
import { compareDate } from '@/utils/common/moment'

function filterUnit(id, arr) {
  for (const item of arr) {
    if (item.id == id) return item
    if (item.children && item.children.length > 0) {
      const _item = filterUnit(id, item.children)
      if (_item) return _item
    }
  }
}

import { listFacilities } from '@/api/house/unmount'
import { addRoom, getRoom, houseManagerList, listProprietor, updateRoom } from '@/api/house/room'
import { listBuildingArray } from '@/api/house/estate'
import selectEstate from '@/components/selectEstate/select-estate.vue'

import rules from './rules/room-add'

export default {
  name: 'roomAdd',
  dicts: [
    'house_orientation',
    'cooperation_type',
    'charge_type'
  ],
  components: { selectEstate },
  props: {
    open: {
      type: Boolean,
      default: false
    },
    roomId: {
      type: String,
      default: ''
    },
    isDetail: {
      default: false
    },
    title: {
      default: '新增房间'
    }
  },
  data() {
    return {
      dialogEstate: false,
      reRender: false,
      floorList: [],
      //楼盘列表
      estateList: [],
      //
      form: {
        facilitiesItemList: [],
        region: [],
        houseInfo: [],
        roomNumber: '',
        estateId: '',
        estateName: '',
        buildingId: '',
        buildingName: '',
        houseNature: '',
        houseType: '',
        houseState: '',
        houseLeaseState: null,
        houseMaintainState: null,
        houseArea: null,
        roomType: '',
        hall: '',
        toilet: '',
        houseOrientation: '',
        waterMeterNumber: null,
        electricMeterNumber: null,
        gasMeterNumber: null,
        houseManagerId: null,
        houseQrCode: null,
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityName: '',
        districtId: '',
        districtName: '',
        streetId: '',
        streetName: '',
        communityId: '',
        communityName: '',
        premisesAddress: '',
        fullAddress: '',
        // delFlag: "",
        unitId: '',
        unitName: '',
        floors: null,
        checkInNumber: null,
        cooperationType: '1',
        chargeType: '1',
        serviceCharge: null,
        feeAmount: null,
        latestPaymentDate: '',
        rentalLicenseNumber: null,
        houseCheckCode: null,
        proprietorId: null,
        proprietorUserId: null
      },
      // 业主列表参数
      proprietorParams: {
        proprietorName: '',//业主名称
        proprietorMobile: '',//业主手机号码
        houseCommissionStatus: '2',//房屋委托:1.待开通;2.已完成(字典字段:house_commission_status)
        proxyServiceStatus: ''//代理服务:1.待开通;2.未完成;3.已完成(字典字段:proxy_service_status)
      },
      rules: rules.apply(this),
      // 房管家列表
      houseManagerList: [],
      //业主列表
      proprietorList: [],
      //设施列表
      facilitiesMap: [],
      // 最晚付款日期选项
      lastPaymentDateOptions: {
        disabledDate(time) {
          //可选今天之后的日期
          return compareDate(time, new Date(), '<=')
        }
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.$attrs.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  watch:{
    visible(val){
      if(val){
        this.init()
      }
    }
  },
  // async created() {
  //   this.init()
  // },
  methods: {
    init() {
      this.reset()
      this.getfacilityList()
      this.getHouseManagerList()
      this.getProprietorList()
      if (this.roomId) {
        this.getRoomDetail()
      } else {
        this.reRender = true
      }
    },
    reset(){
      this.form =  {
        facilitiesItemList: [],
          region: [],
          houseInfo: [],
          roomNumber: '',
          estateId: '',
          estateName: '',
          buildingId: '',
          buildingName: '',
          houseNature: '',
          houseType: '',
          houseState: '',
          houseLeaseState: null,
          houseMaintainState: null,
          houseArea: null,
          roomType: '',
          hall: '',
          toilet: '',
          houseOrientation: '',
          waterMeterNumber: null,
          electricMeterNumber: null,
          gasMeterNumber: null,
          houseManagerId: null,
          houseQrCode: null,
          provinceId: '',
          provinceName: '',
          cityId: '',
          cityName: '',
          districtId: '',
          districtName: '',
          streetId: '',
          streetName: '',
          communityId: '',
          communityName: '',
          premisesAddress: '',
          fullAddress: '',
          // delFlag: "",
          unitId: '',
          unitName: '',
          floors: null,
          checkInNumber: null,
          cooperationType: '1',
          chargeType: '1',
          serviceCharge: null,
          feeAmount: null,
          latestPaymentDate: '',
          rentalLicenseNumber: null,
          houseCheckCode: null,
          proprietorId: null,
        proprietorUserId: null
      }
      this.resetForm('form')
    },
    //获取房管家列表
    getHouseManagerList() {
      let params = {
        roleKey: 'houseKeeper'
      }
      houseManagerList(params).then(response => {
        this.houseManagerList = response.data.map(item => {
          return {
            label: item.userName,
            value: item.userId
          }
        })
      })
    },
    //获取房管家列表
    getProprietorList() {
      listProprietor(this.proprietorParams).then(response => {
        this.proprietorList = response.rows.map(item => {
          return {
            label: item.proprietorName,
            value: item.conUserId
          }
        })
      })
    },
    //合作方式改变
    checkedCooperationType(e) {
      this.form.proprietorId = null
      this.form.proprietorUserId = null
      if (!e) return
      //房屋委托
      if (e == 1) {
        this.proprietorParams.houseCommissionStatus = '2'
        this.proprietorParams.proxyServiceStatus = ''
      }
      // 代理服务
      if (e == 2) {
        this.proprietorParams.houseCommissionStatus = ''
        this.proprietorParams.proxyServiceStatus = '3'
      }
      this.getProprietorList()
    },
    successHandel(item) {
      this.form.estateId = item.estateId
      this.form.estateName = item.estateName
      this.getlistBuilding()
    },
    handleChange() {
      const checkedNodes = this.$refs['houseInfo'].getCheckedNodes()
      const ids = checkedNodes[0].path
      const labels = checkedNodes[0].pathLabels
      let floorList = []
      let number = checkedNodes[0].data.number
      let i = 1
      while (i <= number) {
        floorList.push(i)
        i++
      }
      this.floorList = floorList
      //this.form.estateId = ids[0];
      //this.form.estateName = labels[0];
      this.form.buildingId = ids[0]
      this.form.buildingName = labels[0]
      this.form.unitId = ids[1]
      this.form.unitName = labels[1]
    },
    //检测是否选择区域
    checkedRegion(e) {
      if (this.form.estateId == '' && e) {
        this.$modal.closeAll()
        this.$modal.msgError('请先选择楼盘')
      }
    },
    checkedHouseInfo(e) {
      if (this.form.houseInfo.length == 0 && e) {
        this.$modal.closeAll()
        this.$modal.msgError('请先选择楼栋、单元')
      }
    },

    /** 详情 */
    async getRoomDetail() {
      this.loading = true
      await getRoom(this.roomId).then((response) => {
        let form = response.data

        this.checkedCooperationType(form.cooperationType)
        // let region = [];
        // region.push(response.data.provinceId);
        // region.push(response.data.cityId);
        // region.push(response.data.districtId);
        // region.push(response.data.streetId);
        // region.push(response.data.communityId);
        let houseInfo = []
        houseInfo.push(response.data.buildingId)
        houseInfo.push(response.data.unitId)
        //form.region = region;
        form.houseInfo = houseInfo
        this.form = form
        this.reRender = true
      })
      await this.getlistBuilding()
    },
    /** 查询楼栋、单元集合 */
    getlistBuilding() {
      this.loading = true
      listBuildingArray({ estateId: this.form.estateId }).then((response) => {
        this.estateList = response
        if (this.form.unitId) {
          let data = filterUnit(this.form.unitId, this.estateList)
          let floorList = []
          let number = data.number
          let i = 1
          while (i <= number) {
            floorList.push(i)
            i++
          }
          this.floorList = floorList
        }
      })
    },

    //删除设施
    delfacilities(index) {
      this.form.facilitiesItemList.splice(index, 1)
    },
    //添加设施
    addfacilities() {
      this.form.facilitiesItemList.push({
        facilitiesId: null,
        facilitiesNumber: null,
        facilitiesPrice: null,
        facilitiesState: 1
      })
    },
    /** 查询设施列表 */
    getfacilityList() {
      let params = {
        facilitiesType: 2 // 设施类型（1服务，2设施，3建筑，4卫浴，5餐厨，6娱乐）该页面写死传2
      }
      listFacilities(params).then((response) => {
        this.facilitiesMap = response.data
      })
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.roomId != '') {
            updateRoom(this.form).then((response) => {
              this.$modal.msgSuccess(response.msg)
              this.close()
            })
          } else {
            addRoom(this.form).then((response) => {
              this.$modal.msgSuccess(response.msg)
              this.close()
            })
          }
        }
      })
    },
    cancel() {
      this.close()
    },
    close() {
      this.$emit('closeeldialog')
    }
  }
}
</script>
<style lang="scss" scoped>
.form {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

.el-input::v-deep {
  width: 217px;
}

.avatar-uploader::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader::v-deep .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
